from selenium import webdriver
from selenium.webdriver import ChromeOptions
import json



class Page():
    # 初始化端口
    def __init__(self, flag=0, port='https://copymanga.site/rank'):
        self.port = port
        self.max_time = 10
        self.op(show=int(flag / 2), head=int(flag % 2))
        self.on()

    def on(self):
        driver = webdriver.Chrome(options=self.option)
        driver.maximize_window()
        # driver.implicitly_wait(self.max_time)
        driver.get(self.port)
        self.driver = driver

    def op(self, show=0, head=0):
        option = ChromeOptions()

        # # 以下ip使用自己可使用的代理IP
        # proxy_arr = [
        #     '--proxy-server=http://171.35.141.103:9999',
        #     '--proxy-server=http://36.248.132.196:9999',
        #     # '--proxy-server=http://125.46.0.62:53281',
        #     '--proxy-server=http://219.239.142.253:3128',
        #     '--proxy-server=http://119.57.156.90:53281',
        #     '--proxy-server=http://60.205.132.71:80',
        #     '--proxy-server=https://139.217.110.76:3128',
        #     '--proxy-server=https://116.196.85.150:3128'
        # ]
        # proxy = random.choice(proxy_arr)
        # option.add_argument(proxy)
        #
        if show != 0:  # 是否显示
            option.add_argument('--headless')
        if head != 0:  # 是否去除自动化标识
            option.add_experimental_option('excludeSwitches', ['enable-automation'])
            option.add_experimental_option('useAutomationExtension', False)

        self.option = option

    # 写入
    def ic(self):
        cookies = self.driver.get_cookies()
        with open(file="../cookies.json", mode="w+", encoding="utf-8") as ff:
            cookies = json.dumps(cookies, sort_keys=False, indent=4, separators=(',', ': '))
            ff.write(cookies)

    # 读出
    def oc(self):
        with open(file="../cookies.json", mode="r", encoding="utf-8") as ff:
            cookies = json.load(ff)
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.refresh()


